package selebash;

import com.selebash.Utils;
import com.selebash.annotation.Feature;
import com.selebash.exception.SelebashException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringEscapeUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumFeatures {

    private WebDriver driver;

    public SeleniumFeatures() {
            driver = new FirefoxDriver();
        
    }

    protected Object executeJs(String javaScript) {
        return ((JavascriptExecutor) driver).executeScript(javaScript);
    }

    protected void ensureSelebashInstalled() {
        String result = (String) executeJs("return typeof(selebashElementClick)");
        if (result != null && result.equals("undefined")) {
            String js = String.format("var fileref=document.createElement('script');\n"
                    + "  fileref.setAttribute(\"type\",\"text/javascript\");\n"
                    + "  fileref.setAttribute(\"src\", %s);\n"
                    + "  document.getElementsByTagName(\"head\")[0].appendChild(fileref);\n"
                    + "return 'ok';", "\"https://dl.dropboxusercontent.com/u/8773223/selebash/selebash.js\"");
            result = (String) executeJs(js);
            if (result == null || !result.equals("ok")) {
                throw new SelebashException("Error while try to install selebash to webpage");
            }
        }
    }

    @Feature(value = "захожу на страницу (.*)")
    protected void openUrl(String url) {
        url = Utils.stripQuotes(url);
        driver.get(url);
    }

    @Feature("нажимаю на ссылку (.*)")
    protected void pressLink(String link) {
        ensureSelebashInstalled();
        link = Utils.stripQuotes(link);
        String js = String.format("return selebashSearchA(\"%s\")", link);
        String result = (String) executeJs(js);
        if (result == null) {
            throw new SelebashException("не могу найти элемент " + link);
        }

        driver.findElement(By.id(result)).click();
    }

    @Feature("нажимаю на кнопку (.*)")
    protected void pressButton(String label) {
        ensureSelebashInstalled();
        label = Utils.stripQuotes(label);
        String js = String.format("return selebashSearchInput(\"%s\")", StringEscapeUtils.escapeEcmaScript(label));
        String result = (String) executeJs(js);
        if (result == null) {
            throw new SelebashException("не могу найти элемент " + label);
        }

        driver.findElement(By.id(result)).submit();
    }
    
    @Feature("вижу текст (.*)")
    protected void canSeeText(String text) {
        ensureSelebashInstalled();
        text=Utils.stripQuotes(text);
        Boolean result=(Boolean) executeJs(String.format("return selebashCanSeeText(\"%s\")",StringEscapeUtils.escapeEcmaScript(text)));
        if(result==null || result!=true){
            throw new SelebashException("Не найден текст \"" + StringEscapeUtils.escapeEcmaScript(text)+"\"");
        }
    }
    
    @Feature("Не вижу текст (.*)")
    protected void doNotSeeText(String text) {
        ensureSelebashInstalled();
        text=Utils.stripQuotes(text);
        Boolean result=(Boolean) executeJs(String.format("return selebashCanSeeText(\"%s\")",StringEscapeUtils.escapeEcmaScript(text)));
        if(result==null || result!=false){
            throw new SelebashException("Не найден текст \"" + StringEscapeUtils.escapeEcmaScript(text)+"\"");
        }
    }

    @Feature("ввожу в поле (.*?) текст (.*)")
    protected void enterTextInField(String field, String value) {
        field = Utils.stripQuotes(field);
        value = Utils.stripQuotes(value);

        String js = String.format("return selebashSearchInput(\"%s\")", field);
        String result = (String) executeJs(js);
        if (result == null) {
            throw new SelebashException("не могу найти элемент " + field);
        }

        WebElement irepnumber = driver.findElement(By.id(result));
        irepnumber.sendKeys(value);
    }

    @Feature("вывести сообщение (.*)")
    protected void alert(String message) {
        String script = String.format("alert('%s');", StringEscapeUtils.escapeEcmaScript(message));
        ((JavascriptExecutor) driver).executeScript(script);
    }
}
